import * as UserApi from "@/api/user";
import authority from "@/utils/authority";

const { token = "", user: userinfo = {} } = authority.get() || {};

const user = {
  state: {
    token,
    user: userinfo
  },

  mutations: {
    SET_USER: (state, payload = {}) => {
      Object.assign(state, payload);
    }
  },

  actions: {
    // 登录
    async login({ commit }, userInfo) {
      let data = await UserApi.login({
        phone: userInfo.phone.trim(),
        code: userInfo.code
      });
      data.is_admin = true;
      authority.set(data);
      commit("SET_USER", data);
      commit("SET_PERMISSION_ROUTER");
    },

    // 登出
    logout({ commit }) {
      return UserApi.logout().then(() => {
        commit("SET_USER", {
          token: "",
          name: ""
        });
        authority.clear();
        window.location.reload();
      });
    }
  }
};

export default user;
